import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { Download } from '@/modules/download/entities/download.entity'
import { EEnableStatus } from '@/shared/types/globalEnum'
import { CreateDownloadDto, FindOneDownloadDto, ListPageDownloadDto, ListPaginationDownloadVo, UpdateDownloadDto } from './dto/download.dto'

@Injectable()
export class DownloadService {
  constructor(
    @InjectRepository(Download)
    private downloadRepository: Repository<Download>,
  ) {}

  // 将所有其他记录设为禁用
  async setAllDisable() {
    await this.downloadRepository.update({ useStatus: EEnableStatus.ENABLED }, { useStatus: EEnableStatus.DISABLED })
  }

  create(data: CreateDownloadDto) {
    return this.downloadRepository.save(data)
  }

  async findOne(data: FindOneDownloadDto) {
    return await this.downloadRepository.findOneBy(data)
  }

  async findPage(query: ListPageDownloadDto): Promise<ListPaginationDownloadVo> {
    const { pageNo = 1, pageSize = 10, ...rest } = query
    const [list, total] = await this.downloadRepository.findAndCount({
      where: rest,
      skip: (pageNo - 1) * pageSize,
      take: pageSize,
      order: {
        createdAt: 'DESC',
      },
    })

    return {
      total,
      list,
    }
  }

  async update(downloadId: number, data: UpdateDownloadDto) {
    return this.downloadRepository.update(downloadId, {
      ...data,
      downloadId: undefined,
    })
  }

  remove(downloadId: number) {
    return this.downloadRepository.delete(downloadId)
  }
}
